import { createRouter, createWebHistory } from 'vue-router';
import Layout from '@/layout/index.vue';

// 路由配置
const routes = [
  {
    path: '/',
    redirect: '/dashboard'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Login.vue'),
    meta: { title: '用户登录', public: true }
  },
  {
    path: '/',
    component: Layout,
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '仪表盘' }
      },
      {
        path: 'books',
        name: 'Books',
        component: () => import('@/views/book/BookList.vue'),
        meta: { title: '图书管理' }
      },
      {
        path: 'books/edit/:id',
        name: 'BookEdit',
        component: () => import('@/views/book/BookEdit.vue'),
        meta: { title: '编辑图书' }
      },
      {
        path: 'books/create',
        name: 'BookCreate',
        component: () => import('@/views/book/BookEdit.vue'),
        meta: { title: '新增图书' }
      },
      {
        path: 'redis',
        name: 'RedisManager',
        component: () => import('@/views/redis/RedisManagerNew.vue'),
        meta: { title: 'Redis管理' }
      },
      {
        path: 'profile',
        name: 'UserProfile',
        component: () => import('@/views/UserProfile.vue'),
        meta: { title: '个人资料' }
      }
    ]
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// 路由前置守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - SpringBoot示例` : 'SpringBoot示例';
  
  // 如果是公开页面，直接放行
  if (to.meta.public) {
    next();
    return;
  }
  
  // 检查token是否存在和有效
  const token = localStorage.getItem('token');
  const tokenExpiration = localStorage.getItem('tokenExpiration');
  
  console.log(`路由守卫检查 - 目标路径: ${to.path}`);
  console.log(`Token存在: ${!!token}`);
  console.log(`Token过期时间: ${tokenExpiration}`);
  console.log(`当前时间: ${Date.now()}`);
  
  // 检查token是否过期
  const isTokenExpired = !tokenExpiration || Date.now() > parseInt(tokenExpiration);
  console.log(`Token是否过期: ${isTokenExpired}`);
  
  // 如果没有token或token已过期，清除所有信息并跳转到登录页
  if (!token || isTokenExpired) {
    console.log(`路由守卫阻止访问: token=${!!token}, expired=${isTokenExpired}`);
    if (isTokenExpired) {
      console.log('清除过期token信息');
      // 清除过期的token信息
      localStorage.removeItem('token');
      localStorage.removeItem('tokenExpiration');
      localStorage.removeItem('username');
      localStorage.removeItem('userInfo');
    }
    
    if (to.path !== '/login') {
      next('/login');
      return;
    }
  }
  
  next();
});

export default router;
